package com.api.test;

import java.lang.reflect.Constructor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.api.client.model.ApiErrorHandler;
import com.zyncro.api.model.ErrorServiceApi;

public class ErrorHandlerImpl implements ApiErrorHandler<ErrorServiceApi> {

	private final Log logger = LogFactory.getLog(getClass());

	@Override
	public Class<ErrorServiceApi> getErrorType() {
		return ErrorServiceApi.class;
	}

	@Override
	public void throwException(Object errorObject) throws Exception {

		ErrorServiceApi error = (ErrorServiceApi) errorObject;

		Exception apiException = null;

		try {
			Class<?> exceptionClass = Class.forName(error.getError());
			Constructor<?> constructor = exceptionClass.getConstructor(String.class);
			apiException = (Exception) constructor.newInstance(error.getMessage());

		} catch (Exception e) {
			logger.warn(String.format("Problems parsing api exception '%s'", error.getError()));
		}
		if (apiException != null) {
			throw apiException;
		}
	}
}
